package shop.file.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.common.core.Result;
import shop.common.entity.Image;
import shop.file.service.ImageService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@RestController
@RequestMapping("/api/files")
public class ImageController {

    @Autowired
    private ImageService imageService;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        Image image = imageService.uploadImage(file);
        return Result.ok().data(image);
    }


    @GetMapping("/download/{id}")
    public void download(@PathVariable String id, HttpServletResponse response) {
        Image image = imageService.getById(id);

        try {
            response.setContentType("image/" + image.getSuffix());
            response.getOutputStream().write(image.getData());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException("获取图片失败", e);
        }
    }
}